<template>
  <div>
    <Form class="ivu-mb-16">
      <Button
        type="primary"
        @click="handleAdd"
        v-hasC="{
          name: 'v1-base-navbar-update-navbar',
          flag: 'v1/base/navbar/update-navbar',
        }"
        >新增</Button
      >
    </Form>
    <Table
      :columns="columns"
      :data="list"
      :loading="loading"
      :border="true"
      v-hasC="{ name: 'v1-base-navbar-index', flag: 'v1/base/navbar/index' }"
    >
      <template #image="{ row }">
        <img
          :src="row.http_path"
          @click="callClick(row)"
          style="object-fit: contain; width: 80px; height: 40px"
        />
      </template>
      <template #status="{ row }">
        <Badge v-if="+row.status === 1" status="success" text="正常" />
        <Badge v-if="+row.status === 0" status="error" text="停用" />
      </template>
      <template #nav="{ row }">
        <span v-if="+row.type === 1">栏目</span>
        <span v-if="+row.type === 3">模块</span>
        <span v-if="+row.type === 2">咨询按钮</span>
      </template>
      <template #action="{ row }">
        <a
          @click="handleEdit(row)"
          v-hasC="{
            name: 'v1-base-navbar-update-navbar2',
            flag: 'v1/base/navbar/update-navbar',
          }"
          >编辑</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-base-navbar-delete-navbar',
            flag: 'v1/base/navbar/delete-navbar',
          }"
        ></Divider>
        <a
          @click="handleDelete(row)"
          :class="+row.is_builtin == 1 ? 'active' : 'spanstyle'"
          v-hasC="{
            name: 'v1-base-navbar-delete-navbar',
            flag: 'v1/base/navbar/delete-navbar',
          }"
          >删除</a
        >
      </template>
    </Table>
    <Page
      class="ivu-mt-16"
      show-total
      show-elevator
      show-sizer
      :total="total"
      :current.sync="params.page"
      :page-size="params.pageSize"
      @on-change="changepage"
      @on-page-size-change="changepageSize"
      v-hasC="{ name: 'v1-base-navbar-index', flag: 'v1/base/navbar/index' }"
    ></Page>
    <Modal
      :title="add ? '快捷导航-新增' : '快捷导航-编辑'"
      width="960"
      v-model="modal"
      :mask-closable="false"
      :draggable="true"
      @on-visible-change="$refs.formvid.resetFields()"
    >
      <Form :label-width="118" ref="formvid" :model="formData" :rules="rules">
        <FormItem label="标题名称" prop="name">
          <Input v-model="formData.name" placeholder="广告图标题名称" />
        </FormItem>
        <FormItem label="图标" prop="path" :rules="rules.path">
          <div class="imageUpdate">
            <Upload
              v-model="formData.path"
              :show-upload-list="false"
              :format="['jpg', 'png', 'gif', 'jpeg', 'webp']"
              :action="requestAction"
              :before-upload="beforeUpLoad"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
            >
              <Button
                :loading="uplodloading"
                type="primary"
                class="ivu-ml-8 ivu-mr-8"
                >{{ uplodloading ? "上传中..." : "上传" }}</Button
              >
            </Upload>
            <Button type="success" @click="showImgModel = true">选择</Button>
          </div>
        </FormItem>
        <FormItem label="">
          <img
            v-if="modalimgUrl !== ''"
            :src="modalimgUrl"
            width="100"
            height="100"
            style="object-fit: contain"
          />
          <Icon
            v-if="modalimgUrl !== ''"
            type="ios-trash"
            :size="32"
            @click="modalDel"
            style="cursor: pointer"
          />
        </FormItem>
        <FormItem label="链接" prop="type">
          <RadioGroup v-model="formData.type">
            <Radio :label="1" :disabled="modalIs_builtin == 1 ? true : false">栏目</Radio>
            <Radio :label="3" :disabled="modalIs_builtin == 1 ? true : false">模块</Radio>
            <Radio :label="2" :disabled="modalIs_builtin == 1 ? true : false">咨询按钮</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem v-if="+formData.type === 1" label="栏目" prop="navId">
          <TreeSelect
            v-model="formData.navId"
            :data="tree"
            v-width="200"
            @on-change="changeNav"
            :disabled="modalIs_builtin == 1 ? true : false"
          />
          <Select 
            v-if="showTagList"
            placeholder="请选择标签"
            v-model="tagId" 
            multiple 
            style="width:auto" 
            class="ivu-ml-8">
                <Option v-for="item in tagList" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
        </FormItem>
        <FormItem v-if="+formData.type === 3" label="模块" prop="modelId">
          <Select 
            placeholder="请选择模块"
            v-model="formData.modelId" 
            style="width:160px;"             
            @on-change="changeModel"
            class="ivu-ml-8">
                <Option v-for="item in modelList" :value="+item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
          <Select 
            v-model="tagId2" 
            style="width:auto;"
            multiple 
            class="ivu-ml-8">
                <Option v-for="item in modelTagList" :value="item.id" :key="item.id">{{ item.name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="排序" prop="sort">
          <InputNumber
            v-model="formData.sort"
            :min="1"
            :precision="0"
            :disabled="modalIs_builtin == 1 ? true : false"
          />
        </FormItem>
        <FormItem label="状态" prop="status">
          <Switch
            v-model="formData.status"
            :disabled="modalIs_builtin == 1 ? true : false"
          />
        </FormItem>
      </Form>
      <template #footer>
        <Button @click="handleCancel">取消</Button>
        <Button type="primary" @click="handleSave" :loading="modalLoading"
          >确定</Button
        >
      </template>
    </Modal>
    <Modal v-model="imgModal" footer-hide>
      <p slot="header">查看大图</p>
      <img :src="imgUrl" style="width: 100%; object-fit: cover" />
    </Modal>
    <glo-check v-model="showImgModel" @getImgArr="getImgArr" />
  </div>
</template>
<script>
import { navbarIndex, updateNavbar, deleteNavbar } from '@/api/set'
import { GetNavigation } from '@/api/wsh_user.js'
import { updatefileTemp } from '@/api/set.js'
import Setting from '@/setting'
import util from '@/libs/util'
export default {
  name: 'modalName',
  data () {
    return {
      showImgModel: false,
      add: true,
      modal: false,
      total: 0,
      requestAction: '',
      baseUrl: Setting.request.apiBaseURL,
      modalimgUrl: '',
      uplodloading: false,
      imgModal: false,
      imgUrl: '',
      params: { page: 1, pageSize: 10, is_builtin: 0 },
      formData: {
        id: '',
        name: '',
        status: true,
        sort: null,
        type: 1,
        relation_id: '',
        url: '',
        tag_id:'',
        modelId:'',
        navId:'',
        path: ''
      },
      loading: false,
      rules: {
        name: [{ required: true, message: '请输入广告图标题名称', trigger: 'bulr' }],
        path: [
          { required: true, message: '请选择图片', trigger: 'bulr,change' }
        ],
        modelId:[
          { required: true, message: '请选择模块', trigger: 'bulr,change',type:'number' }
        ],
        navId:[
          { required: true, message: '请选择栏目', trigger: 'bulr,change' }
        ]
      },
      tree: [],
      columns: [
        {
          title: 'id',
          key: 'id',
          width: 60,
          fixed: 'left'
        },
        {
          title: '名称',
          key: 'name',
          width: 150,
          fixed: 'left'
        },
        {
          title: '图标',
          slot: 'image',
          width: 118
        },
        {
          title: '链接导航',
          minWidth: 158,
          slot: 'nav',
          // render: (h, params) => h('span', +params.row.type === 1 ? '导航' : '自定义URL')
        },
        {
          title: '排序',
          key: 'sort',
          width: 118
        },
        {
          title: '状态',
          slot: 'status',
          width: 100
        },
        {
          title: '创建时间',
          key: 'created_at',
          width: 158
        },
        {
          title: '操作',
          slot: 'action',
          width: 118
        }
      ],
      list: [],
      modalLoading: false,
      modalIs_builtin: '',
      modelList:[],
      tagList:[],
      modelTagList:[],      
      tagId:[],
      tagId2:[],
      showTagList:false,      
    }
  },
  created () {
    GetNavigation().then(res => {
      this.tree = res.content
      this.modelList=res.module
      this.tagList=res.content_tag
    })
  },
  mounted () {
    this.requestAction = this.baseUrl + `/v1/upload/images?auth_access_token=${util.cookies.get('token')}&auth_project_id=${localStorage.getItem('currentProject')}`
  },
  methods: {
    initial () {
      this.getData()
    },
    changeNav(e){
      this.showTagList=false
      this.tagId=[]
      this.tree.forEach(item=>{
        if(item.value==e&&item.type!=2){
          this.showTagList=true
        }else{
          item.children.forEach(ele=>{
            if(ele.value==e&&ele.type!=2){
              this.showTagList=true
            }
          })
        }
      })
    },
    changeModel(e){
      this.modelList.forEach(item=>{
        if(item.id==e){
          this.modelTagList=item.tag_list
        }
      })
    },
    changepage (index) {
      this.params.page = index
      this.getData()
    },
    changepageSize (val) {
      this.params.pageSize = val
      this.getData()
    },
    getData () {
      this.loading = true
      navbarIndex().then(res => {
        this.list = res.list
        this.total = res.total
      }).finally(() => {
        this.loading = false
      })
    },
    handleAdd () {
      this.add = true
      this.modal = true
      this.modalimgUrl = ''
      this.formData.path = ''
      this.tagId= []
      this.tagId2=[]     
    },
    handleEdit (row) {
      this.add = false
      this.formData = {
        id: row.id,
        name: row.name,
        status: +row.status === 1 ? true : false,
        sort: row.sort * 1,
        type: row.type * 1,
        relation_id: '',
        url: row.url,
        path: row.path,
        navId :'',
        modelId:'' 
      }
      this.tagId = []
      this.tagId2=[]     
      this.formData.navId = ''
      this.formData.modelId=''   
      if(row.type==1){
        if(row.list_type==1){
          this.showTagList=true
          this.tagId=[...row.tag_id.split(',')]
        }
        this.formData.navId=row.relation_id
      }else if(row.type==3){        
        this.modelList.forEach(item=>{
          if(item.id==row.relation_id){
            this.modelTagList=item.tag_list            
          }
        })    
        this.tagId2=[...row.tag_id.split(',')]  
        this.formData.modelId=+row.relation_id  
      }
      this.modalIs_builtin = row.is_builtin
      this.modalimgUrl = `${row.http_path}`
      this.modal = true
    },
    handleCancel () {
      this.modal = false
      this.modalLoading = false
      this.$refs.formvid.resetFields()
      this.modalimgUrl = ''
    },
    getImgArr (arr) {
      this.modalimgUrl = arr[0]
      this.formData.path = arr[0]
    },
    handleSave () {
      this.$refs.formvid.validate((valid) => {
        if (valid) {
          this.modalLoading = true
          if(+this.formData.type==1){
            this.formData.tag_id=this.tagId.join(',')
            this.formData.relation_id=this.formData.navId
          }else if(+this.formData.type==3){
            this.formData.tag_id=this.tagId2.join(',')
            this.formData.relation_id=this.formData.modelId
          }
          const params = {
            name: this.formData.name,
            path: this.formData.path,
            type: this.formData.type,
            relation_id: this.formData.type !== 2 ? this.formData.relation_id : '',
            url: this.formData.type === 2 ? this.formData.url : '',
            sort: this.formData.sort,
            tag_id:this.formData.tag_id,
            status: this.formData.status === true ? 1 : 0,
            is_builtin: 0
          }
          
          if (this.add) {
            updateNavbar(params).then(res => {
              this.$Message.success('新增成功')
              this.handleCancel()
              this.getData()
            }).catch(() => {
              this.modalLoading = false
            })
          } else {
            updateNavbar(Object.assign({}, params, { id: this.formData.id })).then(res => {
              this.$Message.success('编辑成功')
              this.handleCancel()
              this.getData()
            }).catch(() => {
              this.modalLoading = false
            })
          }

        }
      })
    },
    handleDelete (row) {
      this.$Modal.confirm({
        title: '温馨提示',
        content: '确定删除此项?',
        onOk: () => {
          deleteNavbar({ id: row.id }).then(res => {
            this.$Message.success('删除成功！')
            this.getData()
          })

        }
      })
    },
    callClick (row) {
      this.imgModal = true
      this.imgUrl = row.path
    },
    modalDel () {
      this.modalimgUrl = ''
      this.formData.path = ''
    },
    //上传前
    beforeUpLoad (file) {
      if ((file.type !== 'image/png') && (file.type !== 'image/jpeg') && (file.type !== 'image/jpg')) {
        this.$Message.error({
          content: '请上传 jpg/jpeg 或 png 格式的图片',
          duration: 5,
          closable: true
        })
        return false
      }
      this.formData.path = ''
      this.modalimgUrl = ''
      this.uplodloading = true
    },
    handleUploadSuccess (response) {
      this.uplodloading = false
      this.formData.path = response.data.image_url[0]
      this.modalimgUrl = `${response.data.host}${response.data.image_url[0]}`
      const id = response.data.image_id[0]
      updatefileTemp({ id })
    },
    handleUploadError (error, file, fileList) {
      this.uplodloading = false
      this.$Message.error(error)
    },
  },
}
</script>
<style lang='less' scoped>
.imageUpdate {
  display: flex;
}
.ivu-upload{
  line-height: 1;
}
.delete {
  color: rgb(226, 5, 5);
}
.active {
  color: #ccc;
  cursor: not-allowed;
  pointer-events: none;
}
.spanstyle {
  color: #f00;
  cursor: pointer;
}
</style>
